﻿$(function () {

    //测试代码
    $("#user_name").val("Administrator");
    $("#user_password").val("0123456789");

    //正式代码
    //$("#user_name").val(commons.cookie.get("user_name"));
    //$("#user_password").val(commons.cookie.get("user_password"));

    //是否记录密码
    var isRecord = function () {
        if (commons.cookie.get("user_password")) {
            $("#user_record").prop("checked", true);
        }
    }

    isRecord();

    $("#user_name").focus(function () {
        $("#user_name_error").css("display", "none");
        $("#login_error").css("display", "none");
    });

    $("#user_password").focus(function () {
        $("#user_password_error").css("display", "none");
        $("#login_error").css("display", "none");
    });
});

//登录
var login = function () {
    $("#login_btn").attr({ "disabled": "disabled" });
    $("#login_btn").val("Loging......");
    var userName = $("#user_name").val();
    var userPassword = $("#user_password").val();

    //登录失败按钮
    var loginErrorBtn = function () {
        $("#login_btn").val("登  录    LOGIN");
        $("#login_btn").removeAttr("disabled");
    }

    if (!userName) {
        $("#user_name_error").css("display", "block");
        loginErrorBtn();
        return;
    }
    if (!userPassword) {
        $("#user_password_error").css("display", "block");
        loginErrorBtn();
        return;
    }

    //是否记录密码
    var isRecordPassword = function () {
        if ($("#user_record").is(":checked"))
            commons.cookie.set("user_password", userPassword);
        else
            commons.cookie.del("user_password");
    }

    //登录失败
    var loginError = function (message) {
        $("#login_error").html("*" + message);
        $("#login_error").css("display", "block");
        loginErrorBtn();
    }

    $.ajax({
        type: "POST",
        url: "/authentication/login",
        data: { userName: userName, password: userPassword },
        dataType: "json",
        success: function (result) {
            if (result.Code === 1) {
                commons.cookie.set("user_name", userName);
                isRecordPassword();
                location.href = "/Home";
                return;
            }
            loginError(result.Message);
        },
        error: function () {
            loginError("系统繁忙，请稍后再试");
        }
    });

}